package net.esj.basic.core.utils;

import java.util.AbstractSet;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Set;

import net.esj.basic.pojo.MObject;

public class MObjectSet extends AbstractSet<MObject> implements Set<MObject>,Cloneable, java.io.Serializable{

	/**
	 * 
	 */
	private static final long serialVersionUID = -6214408556796983608L;

	private HashMap<String, MObject> map;

	public MObjectSet() {
		map = new HashMap<String, MObject>();
	}

	public MObjectSet(Collection<? extends MObject> c) {
		map = new HashMap<String, MObject>(Math.max((int) (c.size() / .75f) + 1, 16));
		addAll(c);
	}

	public MObjectSet(int initialCapacity, float loadFactor) {
		map = new HashMap<String, MObject>(initialCapacity, loadFactor);
	}

	public MObjectSet(int initialCapacity) {
		map = new HashMap<String, MObject>(initialCapacity);
	}

	MObjectSet(int initialCapacity, float loadFactor, boolean dummy) {
		map = new LinkedHashMap<String, MObject>(initialCapacity, loadFactor);
	}

	@Override
	public int size() {
		return map.size();
	}

	@Override
	public boolean contains(Object o) {
		if(! (o instanceof MObject)){
			return false;
		}
		MObject mObject = (MObject) o;
		String k = mObject.getId().toString()+"_"+mObject.getMType();
		return map.containsKey(k);
	}

	@Override
	public Iterator<MObject> iterator() {
		return map.values().iterator();
	}

	@Override
	public boolean isEmpty() {
		return map.isEmpty();
	}

	@Override
	public boolean add(MObject e) {
		String k = e.getId().toString()+"_"+e.getMType();
		return map.put(k, e)==null;
	}

	@Override
	public void clear() {
		map.clear();
	}

	@Override
	public Object clone() throws CloneNotSupportedException {
		try {
		    MObjectSet newSet = (MObjectSet) super.clone();
		    newSet.map = (HashMap<String,MObject>) map.clone();
		    return newSet;
		} catch (CloneNotSupportedException e) {
		    throw new InternalError();
		}
	}


}
